package com.xjy.spring.thrift.core;

import com.xjy.spring.thrift.config.BaseServerConfig;
import com.xjy.spring.thrift.config.ThriftServerConfig;
import com.xjy.spring.thrift.zk.ThriftServiceRegister;
import com.xjy.spring.thrift.zk.ZKConstant;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;

public class NonblockingThriftServer extends AbstractThriftServer {

    @Override
    protected void startThriftServer(TProcessor tProcessor, ThriftServerConfig config) throws TTransportException {
        System.err.println("start server, type is Nonblocking, config is " + config);
        TNonblockingServerSocket tnbSocketTransport = new TNonblockingServerSocket(config.getPort());
        TNonblockingServer.Args tnbArgs = new TNonblockingServer.Args(tnbSocketTransport);
        tnbArgs.processor(tProcessor);
        tnbArgs.transportFactory(new TFramedTransport.Factory());
        tnbArgs.protocolFactory(new TCompactProtocol.Factory());
        // 使用非阻塞式IO，服务端和客户端需要指定TFramedTransport数据传输的方式
        TServer server = new TNonblockingServer(tnbArgs);
        // 此处会阻塞
        server.serve();

    }

    @Override
    protected void registerThriftServer(ThriftServerConfig config) {
        new ThriftServiceRegister(ZKConstant.CONNECT_STRING,
                ZKConstant.SESSION_TIMEOUT, ZKConstant.CONNECTION_TIMEOUT)
                .register(new BaseServerConfig(config.getHost(), config.getPort()), ZKConstant.ROOT_PATH,
                        ZKConstant.THRIFT_SERVICE_PATH);
    }

}
